import React, { useCallback, useState } from 'react'
import Taro from '@tarojs/taro'
import {
  Swiper, SwiperItem, View, Image
} from '@tarojs/components'
import LoginVerifyBtn from '@COMPONENTS/Button/LoginVerifyBtn'
import DBConfig from '@CONFIG/DBConfig'
import Images from '@ASSET/Images'
import { getPlatform, openPage } from '@UTILS/common'
import { Analytic_Type } from '@CONSTANTS/analytic'
import style from './HomeBanner.module.scss'

const { isWeb } = getPlatform()

const HomeBanner = ({
  data,
}) => {
  const language = 'zh'
  const [curIndex, setCurIndex] = useState(0)

  const onWebClick = useCallback(() => {
    if (!isWeb) return
    const curBannerData = data[curIndex]
    const { RouteType, RouteData, Title } = curBannerData || {}
    const title = Title[language]
    openPage(RouteType, RouteData)
    Taro.tracker.trackEvent(Analytic_Type.tap_home_banner.eventId, { title })
  }, [curIndex, data])

  const onChange = useCallback(e => {
    setCurIndex(e.detail.current)
  }, [])

  if (!Array.isArray(data) || data.length === 0) return null
  return (
    <View className={style.container}>
      <View onClick={onWebClick}>
        <Swiper
          autoplay
          interval={5000}
          circular={data?.length > 1}
          onChange={onChange}
          className={style.swiperContainer}
        >
          {data.map(item => (
            <SwiperItem key={item.p8Id}>
              <HomeBannerItem language={language} key={item.p8Id} data={item} isSwiper />
            </SwiperItem>
          ))}
        </Swiper>
      </View>
    </View>
  )
}

const RenderBannerImage = ({ onClick, bannerStyle, src }) => (
  <View onClick={onClick} className={style.bannerImage}>
    <Image src={src} className={bannerStyle} mode="scaleToFill" />
  </View>
);

export const HomeBannerItem = ({
  language, data, eventHandle, bannerStyle, showLogin, isSwiper = false, isAuthRedirect
}) => {
  const {
    BannerFileName, RouteType, RouteData, Title
  } = data || {}
  const title = Title[language]
  const src = BannerFileName?.[language]
    ? `${DBConfig.staticBannerImageUrl}${BannerFileName?.[language]}`
    : Images.avatar
  const onClickItem = useCallback(
    () => {
      if (isWeb && isSwiper) return
      openPage(RouteType, RouteData)
      if (eventHandle) {
        eventHandle()
      } else {
        Taro.tracker.trackEvent(Analytic_Type.tap_home_banner.eventId, { title })
      }
    },
    [isSwiper, RouteType, RouteData, eventHandle, title],
  )
  return (
    isAuthRedirect
      ? (
        <LoginVerifyBtn onClick={onClickItem} showLogin={showLogin} loginSuccess={onClickItem}>
          <RenderBannerImage src={src} bannerStyle={bannerStyle || style.bannerItem} />
        </LoginVerifyBtn>
      )
      : <RenderBannerImage onClick={onClickItem} src={src} bannerStyle={bannerStyle || style.bannerItem} />
  )
}

export default HomeBanner
